package cn.com.wangluotongxin.linux.controller;

import cn.com.wangluotongxin.common.web.AjaxResult;
import cn.com.wangluotongxin.linux.dto.FolderInfoDto;
import cn.com.wangluotongxin.linux.form.CreateDirForm;
import cn.com.wangluotongxin.linux.form.DeleteDirForm;
import cn.com.wangluotongxin.linux.service.IFolderService;
import cn.com.wangluotongxin.linux.vo.FolderInfoVo;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Api(tags = "目录")
@RestController
@RequestMapping("/folder")
public class FolderController {

    @Autowired
    private IFolderService folderService;

    @ApiOperation("列表")
    @GetMapping("/list")
    public AjaxResult<List<FolderInfoVo>> list(FolderInfoDto dto) {
        if(StrUtil.isBlank(dto.getPath())) dto.setPath("/");
        return AjaxResult.success(folderService.list(dto));
    }

    @ApiOperation("添加目录")
    @PostMapping("/create/dir")
    public AjaxResult createDir(@RequestBody CreateDirForm form) {
        Assert.isTrue(StrUtil.isNotBlank(form.getDirPath()), "缺少路径");
        Assert.isTrue(StrUtil.isNotBlank(form.getDirName()), "缺少目录名称");
        String dirPath = form.getDirPath().concat("/").concat(form.getDirName());

        folderService.createDirectories(dirPath);
        return AjaxResult.success("目录创建成功");
    }

    @ApiOperation("删除目录")
    @PostMapping("/delete/dir")
    public AjaxResult deleteDir(@RequestBody DeleteDirForm form) {
        Assert.isTrue(StrUtil.isNotBlank(form.getDirPath()), "缺少路径");
        Assert.isTrue(StrUtil.isNotBlank(form.getDirName()), "缺少目录名称");

        folderService.deleteDir(form);
        return AjaxResult.success();
    }

    @ApiOperation("上传目录")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file, @RequestParam("filePath") String filePath, @RequestParam("dirPath") String dirPath) {
        Assert.isTrue(!file.isEmpty(), "请选择文件");
        Assert.isTrue(StrUtil.isNotBlank(filePath), "缺少上传路径");
        Assert.isTrue(StrUtil.isNotBlank(dirPath), "缺少目录路径");
        Assert.isTrue(filePath.indexOf(dirPath) >= 0, "目录路径错误");

        folderService.uploadDir(file, filePath, dirPath);
        return AjaxResult.success("上传成功");
    }
}
